import os
import shutil
import time
import pytest
import allure
from selenium.webdriver.common.by import By
from selenium import webdriver
from page.login import Login
from tools.tools import Tools
from page.agent import Agent


@allure.feature("代理地区模块")
class TestAgent:
    @pytest.fixture(scope='class', autouse=True)
    def classsetup(self):
        """
        类级别初始化
        :return:
        """
        yield
        # # 无论测试是否失败都发送邮件
        self._send_report_email()
        # #类结束后发送报告
        # if not hasattr(pytest,'test_failed'): #检查是否有用用例失败
        #     self._send_report_email()

    """发送报告"""
    def _send_report_email(self):
        """核心流程：生成报告→压缩→发送→清理"""
        report_dir = os.path.abspath('../report')
        zip_path = f'{report_dir}/allure_html.zip'

        # 1. 生成Allure报告
        current_test_path = os.path.abspath(__file__)  # 获取当前文件绝对路径
        Tools().generate_allure_report(current_test_path, report_dir)  # 传入正确路径

        # 2. 压缩报告（直接压缩整个allure_html文件夹）
        shutil.make_archive(
            base_name=f'{report_dir}/allure_html',  # 不要加.zip后缀
            format='zip',
            root_dir=f'{report_dir}/allure_html'
        )

        # 3. 发送邮件（带ZIP附件）
        Tools().email(
            subject='测试报告',
            content='测试执行完毕，附件为详细报告',
            attachments=[zip_path]
        )

        # 4. 发送后删除临时ZIP文件
        if os.path.exists(zip_path):
            os.remove(zip_path)
            self.logger.info('临时ZIP文件已清理')

    """截图"""
    def _take_screenshot(self, step_name):
        """截图并附加到Allure报告"""
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        screenshot_name = f"{step_name}_{timestamp}.png"
        screenshot_path = os.path.join(os.path.abspath('./screenshot'), screenshot_name)
        # 确保截图目录存在
        os.makedirs(os.path.dirname(screenshot_path), exist_ok=True)
        # 截图并保存
        self.driver.save_screenshot(screenshot_path)
        # 附加到Allure报告
        allure.attach.file(screenshot_path, name=step_name,
                           attachment_type=allure.attachment_type.PNG)
        return screenshot_path

    """清理旧截图"""
    def _clean_old_screenshots(self, max_files=20):
        """清理旧的截图文件，保留最近max_files个"""
        screenshot_dir = os.path.abspath('./screenshot')
        if os.path.exists(screenshot_dir):
            files = sorted(os.listdir(screenshot_dir),
                           key=lambda x: os.path.getmtime(os.path.join(screenshot_dir, x)))
            if len(files) > max_files:
                for file in files[:-max_files]:
                    os.remove(os.path.join(screenshot_dir, file))


    @pytest.fixture(autouse=True)
    def methodestupteardown(self):
        """
        方法初始化
        :return:
        """
        self.driver = webdriver.Edge()
        self.driver.maximize_window()
        self.po = Agent(self.driver)
        self.logger = Tools().get_logger("Test.Agent")
        self._clean_old_screenshots()  # 清理旧截图
        self._forward()
        yield
        time.sleep(2)
        self.driver.quit()

    def _forward(self):
        """登录到新增代理商的公共操作"""
        with allure.step('1. 登录系统'):
            self.logger.info('执行前置操作:登录')
            self.po.login_success()
            dy_login = self.po.find_element((By.XPATH, '/html/body/div/div/div[1]/div/div[2]/ul/li[1]')).text
            assert '平台管理' == dy_login, f'登录断言失败,实际值:{dy_login}'
            self.logger.info(f'断言成功:{dy_login}')

        with allure.step('2. 进入代理商'):
            self.po.show_account_manage()
            time.sleep(1)
            dy2 = self.po.find_element(
                (By.XPATH, '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[1]/div[4]/button[2]')).text
            assert '搜索' == dy2
            self.logger.info(f'进入代理商列表成功:{dy2}')

    # @pytest.mark.skip(reason='跳过')
    @allure.story('代理商搜索操作')
    def test_agent_list(self):
        """验证搜索是否正确"""
        with allure.step('输入用户名搜索'):
            try:
                self.po.two_agent()
                dy = self.po.find_element((By.XPATH,
                                           '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr[1]/td[2]/div')).text
                assert '123' == dy
                self.logger.info(f'输入用户名验证通过:{dy}')
                self._take_screenshot('用例通过')
            except Exception as e:
                self._take_screenshot('用例不通过')
                self.logger.error(f'输入用户名验证不通过:{dy}')
                raise

        with allure.step('输入ID搜索'):
            try:
                self.po.three_agent()
                dy = self.po.find_element((By.XPATH,
                                           '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr/td[2]/div')).text
                assert '1458200' == dy
                self.logger.info(f'输入ID验证通过:{dy}')
                self._take_screenshot('通过')
            except Exception as e:
                self._take_screenshot('失败')
                self.logger.error(f'输入id错误:{dy}')
                raise

    # @allure.story('简单数据库断言示例')
    # def test_simple_db_assertion(self):
    #     """最简单的数据库断言示例"""
    #     # 1. 执行SQL查询
    #     sql = 'SELECT * FROM y_user WHERE username = "admin"'
    #     result = self.list_of_dict(sql)  # 调用Base类的方法
    #
    #     # 2. 基本断言
    #     assert len(result) > 0, "未找到用户名为admin的记录"
    #
    #     # 3. 字段值断言
    #     admin_user = result[0]  # 获取第一条记录
    #     assert admin_user['pwd'] == 'ebcbf97ec1d80c0388d39bf508039baa', "管理员状态不正确"
    #     assert admin_user['pk_id'] == 1, "管理员邮箱不正确"

        # with allure.step('输入地区类型'):
        #     self.po.four_agent()
        #     dy = self.po.find_element((By.XPATH,
        #                                '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr/td[4]/div')).text
        #     assert '北方古镇' == dy
        #     self.logger.info(f'输入类型验证通过:{dy}')

    # @allure.story('代理商ID搜索')
    # def test_agent_ID(self):
    #     """验证ID是否通过"""
    #     with allure.step('输入ID'):
    #         self.po.three_agent()
    #         dy = self.po.find_element((By.XPATH,
    #                                    '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr/td[2]/div')).text
    #         assert '1458200' == dy
    #         self.logger.info(f'输入ID验证通过:{dy}')

    # @allure.story('输入用户名')
    # def test_agent_username(self):
    #     """验证用户名"""
    #     with allure.step('输入用户名'):
    #         self.po.two_agent()
    #         dy = self.po.find_element((By.XPATH,
    #                                    '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/table/tbody/tr[1]/td[2]/div')).text
    #         assert '123' == dy
    #         self.logger.info(f'输入用户名验证通过:{dy}')

    # @allure.story('输入类型')
    # def test_agent_leixing(self):
    #     """验证类型是否通过"""
    #     with allure.step('输入类型'):
    #         self.po.four_agent()
    #         dy = self.po.find_element((By.XPATH,
    #                                    '/html/body/div/div/div[2]/div/div[2]/div[2]/div/div[3]/div[3]/div')).text
    #         assert '暂无数据' == dy
    #         self.logger.info(f'输入类型验证通过:{dy}')

if __name__ == '__main__':
    # 确保截图目录存在
    os.makedirs(os.path.abspath('./screenshots'), exist_ok=True)
    # 生成Allure原始数据
    pytest.main(['./Case', '-v', '--alluredir=./report/allure_raw'])

    # 生成HTML报告（需提前安装Allure命令行工具）
    os.system('allure generate ./report/allure_raw -o ./report/allure_html --clean')
    os.system('allure open ./report/allure_html')  # 自动打开报告
